package com.lz.ui_lib.component;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import androidx.annotation.Nullable;

import com.lz.ui_lib.BlurUtil;
import com.lz.ui_lib.R;

/**
 * 模糊
 * <p>
 * Created by liuyakui on 2022/2/13.
 */
public class BlurComponent extends LinearLayout implements SeekBar.OnSeekBarChangeListener {
    private ImageView mImageView;
    private boolean blur = true;
    private Bitmap mBitmap;

    public BlurComponent(Context context) {
        this(context, null);
    }

    public BlurComponent(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BlurComponent(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.ui_blur, this, true);
        buildBitmap();
        initView();
    }

    private void buildBitmap() {
        /**
         * IllegalStateException if the bitmap is not mutable
         *
         * 高斯模糊算法，采用的是改变Pixels达到模糊效果，但是
         * mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.download);
         * 返回的是一个immutalbe的bitmap，不能用setPixels, 所以采用Drawable -> bitmap的方式
         * 得到一个Bitmap
         */
        mBitmap = Bitmap.createBitmap(620, 820, Bitmap.Config.ARGB_8888);
        //drawable -> bitmap
        final Drawable drawable = getResources().getDrawable(R.mipmap.blur_img);
        assert drawable != null;
        final Canvas canvas = new Canvas(mBitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());//一定要setBounds(), 不然什么都画不出来
        drawable.draw(canvas);
    }

    private void initView() {
        mImageView = findViewById(R.id.blur_image);
        mImageView.setImageBitmap(mBitmap);
        mImageView.setAlpha(0f);

        SeekBar mSeekBar = (SeekBar) findViewById(R.id.blur_seek);
        assert mSeekBar != null;
        mSeekBar.setOnSeekBarChangeListener(this);
        mSeekBar.setMax(100);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (progress > 1 && blur) {
            mBitmap = BlurUtil.doBlur(mBitmap, 25, true);
            blur = false;
        }
        float alpha = (float) progress / 100;
        if (alpha > 1.0) {
            alpha = 1.0f;
        } else if (alpha < 0) {
            alpha = 0.0f;
        }
        Log.i("progress", "alpha: " + alpha);
        mImageView.setAlpha(alpha);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}